import time
import math
import sys

class Stdout_progressbar:
    def __init__(self, max_num, show=True, max_length=50) -> None:
        interval = math.ceil(max_num / max_length)
        length = math.ceil(max_num / interval)
        
        self.interval = interval
        self.length = length
        self.max_num = max_num
        self.time = 0
        self.show = show
        self.skip_n = 1

    def reset(self, skip_n=1):
        self.time = time.perf_counter()
        self.skip_n = skip_n

    def update(self, now_num): # num从1开始
        if not self.show:
            return 0
        
        if now_num == 1:
            elapse = time.perf_counter() - self.time
            if elapse < 1:
                print(f"{1/elapse:.1f} step(frame) per second, eta {elapse*(self.max_num - 1)/self.skip_n:.1f}s")
            else:
                print(f"{elapse:.1f} second per step(frame), eta {elapse*(self.max_num - 1)/self.skip_n:.1f}s")

        # 每一次都更新
        elapse = time.perf_counter() - self.time
        i = now_num // self.interval
        percentage = round(now_num / self.max_num * 100)
        print("\rProcess: {}%: |".format(percentage), "-" * (i), end="")
        print(" "*(self.length - i),"|",f"use {elapse:.1f}s   ", end="")
        sys.stdout.flush()

        if now_num == -1: # 代表结束
            elapse = time.perf_counter() - self.time
            print("\nprocess finished!")
            print(f"totally use {elapse:.1f}s")
            sys.stdout.flush()

        return percentage
